﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TvGuide.UI.Models;
using TVGuide.Common;
using TVGuide.Parser;
using System.Data;
using TVGuide.DataAccess;

namespace TvGuide.UI.Controllers
{
    public class OnlineTVController : BaseController
    {
        public static List<OnlineSessionInfo> sessionInfo = new List<OnlineSessionInfo>();

        //
        // iFrame format:  
        // <iframe src="/online_players/torrentstream/player.html?contentId={torrentContentID}" style="width: 720px; height: 500px; border: none; background-color: #000;" frameborder="0"></iframe>
        // GET: /OnlineTV/
        private int lang;

        [HttpGet]
        public ActionResult OnlineTV(string lng, string name)
        {
            this.lang = Utils.LanguageSelect(lng);
            OnlineTVData Onlinetvdata = new OnlineTVData(lang);
            // Retrieve channel name from name as name is chanName-tv-online

            string chanName = "H1";
           
            if (!String.IsNullOrEmpty(name))
            {
                chanName = name.Split(new string[] { "-tv" }, StringSplitOptions.None)[0];
            }
            ChannelShowList channel = ProgramData.chlist.Find(o => o.Name == chanName);
            ViewData["lng"] = lng;
            ViewData["chId"] = channel.ID;

            ViewData["armlink"] = "/"+"arm"+"/Watch/" + name;
            ViewData["englink"] = "/"+"eng"+"/Watch/" + name;
            string playercode = channel.StreamUrl;
            string torrentContentID = channel.TorrentContentID;
            playercode = playercode.Replace("{torrentContentID}", torrentContentID);
            ViewData["playerCode"] = playercode;
            if (playercode.IndexOf("torrentstream") == -1 && playercode.IndexOf("1ttv") == -1)
            {
                ViewData["player_help"] = "none";
            }
            else
            {
                ViewData["player_help"] = "block";
            }

            
            var a = Request.RawUrl;
            ViewData["pageUrl"] = "http://www.tvcuyc.am/"+lng+"/Watch/" + chanName+"-tv-online";
            ViewData["imgUrl"] = "http://www.tvcuyc.am" + channel.FBImgUrl;
            ViewData["displayName"] = channel.DispName;
            ViewData["chOnlineMetaDesc"] = !string.IsNullOrEmpty(channel.MetaDescription) ? channel.MetaDescription : (channel.Name +" tv - Online serials and other programs on " + channel.Name + " tv online.");
            ViewData["name"] = channel.Name;
            ViewData["title"] = ViewData["name"];
            //Getting facebook comments
            string commentUrl = "https://graph.facebook.com/comments/?ids=http://www.tvcuyc.am/"+lng+"/Watch/" + chanName + "-tv-online";
            string comments = TVGuide.Parser.HTTPClient.GetSiteContent(commentUrl);
            ViewData["facebookComments"] = comments;

            DbAccessHelper access_helper = new DbAccessHelper();

            var prData = new ProgramData(lang);
            prData.NowRuning(DateTime.Now.AddHours(Utils.ZoneHour), lng);
            var currentPrograms = prData.NowRunnList.Where(x => x.ChName == chanName && x.Date <= DateTime.Now.AddHours(Utils.ZoneHour));
            var currentProgram = currentPrograms.LastOrDefault();
            // Show title in the following format: <chnal name> TV Online - <program name>
            if (currentProgram != null)
            {
                ViewData["displayName"] += " Online - " + prData.TranslateToCurrentLang(currentProgram.PrName);
                string link = "http://tvcuyc.am/" + Utils.LanguageSelectToString(this.lang) + "/Watch/" + currentProgram.ChName + "-tv-online";
                string scheduleLink = "/" + Utils.LanguageSelectToString(this.lang) + "/schedule/" + currentProgram.ChName + "-tv/" + currentProgram.chID + "/" + 1;
                ViewData["displayName"] = "<a target='_blank' class='tv-listings-link' href='" + scheduleLink + "'>" + ViewData["displayName"] + "</a>";
                // FB share link
                string HTMLdecodedName = prData.TranslateToCurrentLang(HttpUtility.HtmlDecode(prData.TranslateToCurrentLang(currentProgram.PrName)));
                ViewData["link"] = HttpUtility.HtmlEncode("http://www.facebook.com/dialog/feed?app_id=197849216924945&display=popup&link=" + link + "&picture=" + ViewData["imgUrl"] + "&name=" + HTMLdecodedName + "&redirect_uri=http://tvcuyc.am/close.html");
            }

            return View("OnlineTV", Onlinetvdata); 
        }

        [HttpGet]
        public JsonResult NotifyWatcher(int chId)
        {
            Session["qaq"] = "qaq";
            var currentInfoList = sessionInfo.Where(x => x.SessionID == Session.SessionID && x.ChannelId == chId).ToList();

            var currentInfo = currentInfoList.Count > 0 ? currentInfoList.First() : new OnlineSessionInfo();

            currentInfo.LastNotified = DateTime.Now;
            currentInfo.ChannelId = chId;
            currentInfo.SessionID = Session.SessionID;

            if (!sessionInfo.Contains(currentInfo))
            {
                sessionInfo.Add(currentInfo);
            }

            return Json(sessionInfo.Where(x => x.ChannelId == chId && (DateTime.Now - x.LastNotified).TotalMinutes < 1).Count(), JsonRequestBehavior.AllowGet);
        }
    }

    public class OnlineSessionInfo
 
    {
        public string SessionID { get; set; }
        public int ChannelId { get; set; }
        public DateTime LastNotified { get; set;  }

    }
}
